package com.wenhao.lock.eightlock;

import java.util.concurrent.TimeUnit;

/**
 *
 * 八锁问题的关键就是确定synchronized持有的是哪一个锁对象
 *
 * @author Wenhao Tong
 * @create 2021-08-19 17:38
 */
public class Test2 {
    public static void main(String[] args) throws InterruptedException {
    Phone2 phone = new Phone2();

    new Thread(() -> {
        try {
            phone.sendSms();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }).start();

    TimeUnit.SECONDS.sleep(1);

    new Thread(() -> {
        phone.hello();
    }).start();

}
}

class Phone2 {

    /**
     * 锁的对象是方法的调用者，谁先拿到谁就先执行
     */

    public synchronized void sendSms() throws InterruptedException {
        TimeUnit.SECONDS.sleep(2);
        System.out.println("sendSms...");
    }

    public synchronized void call() {
        System.out.println("call...");
    }

    /**
     * 因为不需要获取锁，所以在sendSms()方法延迟之后会先执行
     */
    public void hello() {
        System.out.println("hello...");
    }
}

